package com.blue.base.demo.redis;

import com.blue.base.common.exception.BaseException;
import com.blue.base.redis.annotation.RedisLock;
import com.blue.base.redis.bean.LockTemplate;
import com.blue.base.redis.bean.RedisLockInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author liulei
 * @version 1.0
 */
@Slf4j
@Service
public class RedisTestService {

    @Autowired
    private LockTemplate lockTemplate;

    /**
     * 注解分布式锁
     */
    @RedisLock(keys = "{#key}")
    public void annoLockMethod(Integer index, String key) throws InterruptedException {
        Thread.sleep(15000);
        log.info("redis加锁方法:{},{}", index, key);
    }

    /**
     * 直接分布式锁
     */
    public void directLockMethod(String key) throws Exception {
        RedisLockInfo lock = lockTemplate.lock(key, 20000, 2000);
        if (null == lock) {
            throw new BaseException(500, "尝试获取锁失败，稍后再试");
        }
        log.info("获取到了锁....{}", key);
        try {
            Thread.sleep(10000);
        } catch (Exception e) {
            log.error("业务异常，抛出异常并释放锁");
            throw e;
        } finally {
            log.info("解锁:{}", key);
            lockTemplate.releaseLock(lock);
        }
    }
}
